package com.cheems.cheems_spring_ai.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.cheems.cheems_spring_ai.common.ErrorCode;
import com.cheems.cheems_spring_ai.domain.Role;
import com.cheems.cheems_spring_ai.domain.User;
import com.cheems.cheems_spring_ai.domain.UserRole;
import com.cheems.cheems_spring_ai.domain.vo.UserVo;
import com.cheems.cheems_spring_ai.exception.BusinessException;
import com.cheems.cheems_spring_ai.mapper.UserMapper;
import com.cheems.cheems_spring_ai.mapper.UserRoleMapper;
import com.cheems.cheems_spring_ai.service.UserService;
import com.cheems.cheems_spring_ai.utils.JwtUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.math.BigInteger;
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;

/**
 * @author lenovo
 * @description 针对表【user】的数据库操作Service实现
 * @createDate 2025-02-24 15:57:50
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User>
        implements UserService {

    @Value("${heanu.app.app-id}")
    private String appid;

    @Value("${heanu.app.app-secret}")
    private String secret;

    @Resource
    private UserMapper userMapper;

    @Resource
    private UserRoleMapper userRoleMapper;

    /**
     * 登录
     * @param code
     * @return
     */
    @Override
    public UserVo login(String code) {
        //创建httpClient
        HttpClient httpClient = HttpClient.newHttpClient();
        String url = "https://oauth.henau.edu.cn/oauth2_server/access_token?appid="+appid+"&secret="+secret+"&code=" + code + "&grant_type=authorization_code";

        // 发送 GET 请求并处理响应
        try {
            HttpRequest request = HttpRequest.newBuilder()
                    .uri(URI.create(url))
                    .GET()
                    .build();

            HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

            // 解析响应
            String responseBody = response.body();
            // 这里可以使用 JSON 解析库（如 Jackson 或 Gson）来解析 responseBody
            //获取access_token和henau_openid
            // 例如：

            JSONObject jsonObject = JSON.parseObject(responseBody);

            String accessToken = jsonObject.getJSONObject("data").getString("access_token");
            String henauOpenid = jsonObject.getJSONObject("data").getString("henau_openid");

            //请求获取用户信息
            String userInfoUrl = "https://oauth.henau.edu.cn/oauth2_server/userinfo?access_token="+accessToken+"&henau_openid="+henauOpenid;
            try {
                request = HttpRequest.newBuilder()
                        .uri(URI.create(userInfoUrl))
                        .GET()
                        .build();

                response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

                // 解析响应
                String responseBodyUser = response.body();
                // 这里可以使用 JSON 解析库（如 Jackson 或 Gson）来解析 responseBody
                //获取access_token和henau_openid
                // 例如：
                JSONObject jsonObjectUser = JSON.parseObject(responseBodyUser);

                String user_name = jsonObjectUser.getJSONObject("data").getString("user_name");
                String user_number = jsonObjectUser.getJSONObject("data").getString("user_number");
                String avatar_url = jsonObjectUser.getJSONObject("data").getString("user_avatar_url");
                String user_phone = jsonObjectUser.getJSONObject("data").getString("user_phone");

                // 根据 henau_number 查询用户是否存在
                User user = userMapper.selectOne(new QueryWrapper<User>().eq("henau_number", user_number));
                if (user == null) {
                    // 用户不存在，则插入新用户
                    user = new User();
                    user.setAvatarImg(avatar_url);
                    user.setUserPhone(user_phone);
                    user.setUserName(user_name);
                    user.setHenauNumber(user_number);
                    user.setHenauOpenid(henauOpenid);
                    userMapper.insert(user);
                    //给用户分配默认角色
                    UserRole userRole = new UserRole();
                    userRole.setUserId(BigInteger.valueOf(user.getId()));
                    userRole.setRoleId(BigInteger.valueOf(2));
                    userRoleMapper.insert(userRole);
                } else {
                    user.setAvatarImg(avatar_url);
                    user.setUserPhone(user_phone);
                    user.setUserName(user_name);
                    user.setHenauNumber(user_number);
                    user.setHenauOpenid(henauOpenid);
                    // 用户存在，则更新用户信息
                    UpdateWrapper<User> updateWrapper = new UpdateWrapper<>();
                    updateWrapper.eq("henau_openid", henauOpenid);
                    userMapper.update(user, updateWrapper);
                }

                //查询用户的角色信息
                Role role = userMapper.queryRole(user.getId());
                //生成jwt密钥
                String token = JwtUtil.createToken(user);

                log.info("生成的token:"+token);
                //封装vo返回对象
                UserVo userVo = new UserVo();
                BeanUtils.copyProperties(user,userVo);
                userVo.setRole(role.getRoleName());
                userVo.setToken(token);
                log.info("登录成功:"+userVo.getUserName());
                log.info("登录成功:"+userVo.getHenauNumber());
                log.info("登录成功:"+userVo.getToken());
                //返回对象user
                return userVo;
            }
            catch (Exception e){
                throw new Exception("获取用户信息失败", e);
            }
        } catch (Exception e) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
    }

    /**
     * 获取用户信息
     * @param request
     * @return
     */
    @Override
    public UserVo getUserInfo(HttpServletRequest request) {
        String henauNumber = request.getAttribute("henauNumber").toString();
        User user = userMapper.selectOne(new QueryWrapper<User>().eq("henau_number", henauNumber));
        Role role = userMapper.queryRole(user.getId());
        UserVo userVo = new UserVo();
        BeanUtils.copyProperties(user,userVo);
        userVo.setRole(role.getRoleName());
        return userVo;
    }
}




